<?php

namespace admin\models;

use ijony\helpers\File;
use ijony\helpers\Folder;
use ijony\helpers\Image;
use ijony\helpers\Utils;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;

/**
 * This is the model class for table "{{%cases}}".
 *
 * @property string $id 案例 ID
 * @property string $name 名称
 * @property string $preview 主图
 * @property string $developer 开发商
 * @property string $age 年代
 * @property string $description 简介
 * @property int $created_at 创建时间
 * @property int $updated_at 修改时间
 * @property int $sort 排序
 * @property int $status 状态
 *
 * @property array $product_ids
 * @property array $galleries 组图数据
 *
 * @property \admin\models\CaseGalleries[] $gallery
 */
class Cases extends \common\models\Cases
{

    public $product_ids = [];
    public $galleries = [
        'image' => [],
        'thumb' => [],
    ];

    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }

    public function rules()
    {
        return ArrayHelper::merge(parent::rules(), [
            [['sort'], 'default', 'value' => 0],
            [['product_ids', 'galleries'], 'safe'],
        ]);
    }

    public function attributeLabels()
    {
        return ArrayHelper::merge(parent::attributeLabels(), [
            'product_ids' => '关联产品',
        ]);
    }

    public function afterFind()
    {
        parent::afterFind();

        $this->product_ids = CaseProducts::find()->select('product_id')->where(['case_id' => $this->id])->column();

        if($this->gallery){
            foreach($this->gallery as $gallery){
                $this->galleries['image'][] = $gallery->file;
                $this->galleries['thumb'][] = Image::getImg($gallery->file, 170, 170);
            }
        }
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);

        if(isset($changedAttributes['preview']) && $changedAttributes['preview'] != $this->preview){
            File::delFile($changedAttributes['preview'], true);
        }

        CaseProducts::deleteAll(['case_id' => $this->id]);

        if($this->product_ids){
            foreach($this->product_ids as $product_id){
                (new CaseProducts(['case_id' => $this->id, 'product_id' => $product_id]))->save();
            }
        }

        if($this->gallery){
            foreach($this->gallery as $gallery){
                if (!isset($this->galleries['image']) || !in_array($gallery->file, $this->galleries['image'])) {
                    $gallery->delete();
                }
            }
        }

        CaseGalleries::deleteAll(['case_id' => $this->id]);

        if(isset($this->galleries['image']) && $this->galleries['image']){
            foreach($this->galleries['image'] as $gallery){
                (new CaseGalleries(['case_id' => $this->id, 'file' => $gallery]))->save();
            }
        }

        Folder::clearBuffer(Yii::$app->user->id);
    }

    public function getGallery()
    {
        return $this->hasMany(CaseGalleries::className(), ['case_id' => 'id']);
    }

    public function getProductSelectData()
    {
        $categories = Categories::find()->where(['status' => Categories::STATUS_ACTIVE])->all();

        foreach($categories as $category){
            $return[$category->name] = Products::find()->select('name')->where(['category_id' => $category->id])->indexBy('id')->column();
        }

        return $return;
    }

    public function getStatus()
    {
        $datas = $this->getStatusSelectData();

        return isset($datas[$this->status]) ? $datas[$this->status] : '';
    }

    public function getStatusLabel()
    {
        if($this->status == self::STATUS_ACTIVE){
            $class = 'label-primary';
        }else{
            $class = 'label-danger';
        }

        return Utils::label($this->getStatus(), $class);
    }

    public function getStatusSelectData()
    {
        return [
            self::STATUS_UNACTIVE => '禁用',
            self::STATUS_ACTIVE => '启用',
        ];
    }

    public static function getOptions($where = null)
    {
        $query = Cases::find()->select('name');

        if($where){
            $query->where($where);
        }

        $datas = $query->indexBy('id')->column();
        $params = ['prompt' => '请选择'];

        return Html::renderSelectOptions(null, $datas, $params);
    }
}
